<?php
require_once('../classes/config.inc.php');
require_once('../classes/Session.php');
require_once('../classes/Database.php');
include('../classes/Form.php');

$session = new UserSession();
$session->open();

if(isset($_POST['action']) && $_POST['action'] == "logout" && $session->check()){
	$session->destroy();
	echo "logged_out";
}
elseif(isset($_POST['action']) && $_POST['action']=="forget_pass"){
	$random_pasw = substr(md5(rand()),0,8);
	$verify = "SELECT * FROM ". TABLE_USERS ." WHERE(email='". $form->get("email") ."')";
	$db = new MYSQLDatabase(DB_SERVER,DB_USER,DB_PASS,DB_DATABASE);
		try {
			$db->connect();
			$link = $db->query($verify);
			if($link!=false && mysql_num_rows($link)>0){
				$sql = "UPDATE ". TABLE_USERS ."SET pass='".md5($random_pasw)."' WHERE(email='".$form->get("email")."')";
				$link = $db->query($sql);
				if($link){
					$mailer = new Mail("Jobbhjelper: Password reset","Your password has been changed to: ".$random_pasw);
					$mailer->send($form->get("email"));
					if($mailer->isSended()){
						echo "You successfully changed your password. Please wait check your mail for the current password.";
					}
					else{
						echo "The email with your password in it hasn't been send. Try resetting password.";
					}
				}
				else{
					echo "Error: Your password is not reset. Try again please.";
				}
			}
			else {
				echo "Given email is not registered on this site.";
			}
		}catch (Exception $e){
			echo "Database problems: ".$e->getMessage();
		}
}
elseif(isset($_POST['action']) && $_POST['action'] == "login" && !$session->check()){
	$form = new Form();
	$formElements = array("email" => 1,"pass" => 1);
	$form->open($formElements);
	
	if($form->isValidForm()){
		$db = new MYSQLDatabase(DB_SERVER,DB_USER,DB_PASS,DB_DATABASE);
		$login_sql = "SELECT * FROM ". TABLE_USERS ." WHERE(email='".$form->get("email")."' AND pass='".$form->get("pass")."') LIMIT 0,1";
		try {
			$db->connect();
			$link = $db->query($login_sql);
			if(mysql_num_rows($link)>0){
				$res = mysql_fetch_array($link);
				$session->save($res["id"],$res["email"],$res["level"]);
				echo "yes";
			}
			else{
				echo "no";
			}
		}catch (Exception $e){
			$error='Error: ' . $e->getMessage();
		}
	}
	else
	{
	 echo "no valid form!";
	}
}else{
	echo "no action!";
}
?>